/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2024 All Rights Reserved.
 */
package com.alipay.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.*;
import com.alipay.api.request.AntMerchantExpandOrderQueryRequest;
import com.alipay.api.request.AntMerchantExpandShopCreateRequest;
import com.alipay.api.request.AntMerchantExpandShopPageQueryRequest;
import com.alipay.api.request.AntMerchantExpandShopQueryRequest;
import com.alipay.api.response.AntMerchantExpandOrderQueryResponse;
import com.alipay.api.response.AntMerchantExpandShopCreateResponse;
import com.alipay.api.response.AntMerchantExpandShopPageQueryResponse;
import com.alipay.api.response.AntMerchantExpandShopQueryResponse;
import com.alipay.demo.service.AntMerchantShopService;
import com.alipay.demo.util.AlipayApiCallback;
import com.alipay.demo.util.AlipayApiTemplate;
import com.alipay.demo.util.AlipaySdkUtil;
import com.alipay.demo.vo.OpenResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jishupei.jsp
 * @version : AntMerchantShopServiceImpl, v0.1 2024年03月06日 3:10 下午 jishupei.jsp Exp $
 */
@Service
public class AntMerchantShopServiceImpl implements AntMerchantShopService {
    private static final Logger logger = LogManager.getLogger(AntMerchantShopServiceImpl.class);

    @Autowired
    private AlipaySdkUtil alipaySdkUtil;

    @Override
    public AntMerchantExpandShopPageQueryResponse queryShopIdByPage(long pageNum, long pageSize) {
        AntMerchantExpandShopPageQueryRequest request = new AntMerchantExpandShopPageQueryRequest();
        AntMerchantExpandShopPageQueryModel model = new AntMerchantExpandShopPageQueryModel();
        model.setPageSize(pageSize);
        model.setPageNum(pageNum);
        model.setIpRoleId(alipaySdkUtil.getPid());
        request.setBizModel(model);
        try {
            AntMerchantExpandShopPageQueryResponse response = alipaySdkUtil.execute(request);
            logger.info(response.getBody());
            if (response.isSuccess()) {
                logger.info("ant.merchant.expand.shop.page.query调用成功");
                if (!CollectionUtils.isEmpty(response.getShopInfos())) {
                    return response;
                }
            } else {
                logger.error("ant.merchant.expand.shop.page.query调用失败" + JSON.toJSONString(response));
            }
        } catch (Exception e) {
            logger.error("ant.merchant.expand.shop.page.query调用失败", e);
        }
        return null;
    }

    @Override
    public OpenResponse<AntMerchantExpandShopQueryResponse> queryByShopId(String shopId) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<AntMerchantExpandShopQueryResponse, AntMerchantExpandShopQueryResponse>() {
            @Override
            public AntMerchantExpandShopQueryResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AntMerchantExpandShopQueryRequest request = new AntMerchantExpandShopQueryRequest();
                AntMerchantExpandShopQueryModel model = new AntMerchantExpandShopQueryModel();

                // 设置门店ID
                model.setShopId(shopId);

                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public AntMerchantExpandShopQueryResponse getData(AntMerchantExpandShopQueryResponse response) {
                return response;
            }

            @Override
            public String getApiName() {
                return "ant.merchant.expand.shop.query";
            }
        });
    }

    @Override
    public OpenResponse<String> create(String shopName, String shopCategory, String storeId) {
        return AlipayApiTemplate.execute(new AlipayApiCallback<String, AntMerchantExpandShopCreateResponse>() {

            @Override
            public AntMerchantExpandShopCreateResponse process() throws AlipayApiException {
                // 构造请求参数以调用接口
                AntMerchantExpandShopCreateRequest request = new AntMerchantExpandShopCreateRequest();
                AntMerchantExpandShopCreateModel model = new AntMerchantExpandShopCreateModel();

                // 设置经营地址
                AddressInfo businessAddress = new AddressInfo();
                businessAddress.setProvinceCode("510000");
                businessAddress.setCityCode("510100");
                businessAddress.setDistrictCode("510107");
                businessAddress.setAddress("益州大道中段1999号");
                model.setBusinessAddress(businessAddress);

                // 设置门店类目
                model.setShopCategory(shopCategory);

                // 设置外部门店编号
                model.setStoreId(storeId);

                // 设置门店类型，01表示直营
                model.setShopType("01");

                // 设置商户角色ID
                model.setIpRoleId(alipaySdkUtil.getPid());

                // 设置门店名称
                model.setShopName(shopName);

                request.setBizModel(model);

                return alipaySdkUtil.execute(request);
            }

            @Override
            public String getData(AntMerchantExpandShopCreateResponse response) {
                return response.getOrderId();
            }

            @Override
            public String getApiName() {
                return "ant.merchant.expand.shop.create";
            }
        });
    }

    @Override
    public AntMerchantExpandOrderQueryResponse orderQuery(String orderId) {
        // 构造请求参数以调用接口
        AntMerchantExpandOrderQueryRequest request = new AntMerchantExpandOrderQueryRequest();
        AntMerchantExpandOrderQueryModel model = new AntMerchantExpandOrderQueryModel();

        // 设置申请单id
        model.setOrderId(orderId);

        request.setBizModel(model);
        try {
            AntMerchantExpandOrderQueryResponse response = alipaySdkUtil.execute(request);
            logger.info(response.getBody());
            if (response.isSuccess()) {
                logger.info("ant.merchant.expand.order.query调用成功");
            } else {
                logger.error("ant.merchant.expand.order.query调用失败" + JSON.toJSONString(response));
            }
            return response;
        } catch (Exception e) {
            logger.error("ant.merchant.expand.order.query调用失败", e);
        }
        return null;
    }

    @Override
    public List<ShopQueryOpenApiVO> queryNormalShopInfos() {
        List<ShopQueryOpenApiVO> result = new java.util.ArrayList<>();
        int currentPage = 1, pageSize = 10;
        long totalPages;
        do {
            AntMerchantExpandShopPageQueryResponse pageQueryResponse = queryShopIdByPage(currentPage, pageSize);
            if (pageQueryResponse == null) {
                break;
            }
            if (!CollectionUtils.isEmpty(pageQueryResponse.getShopInfos())) {
                // 仅获取正常状态的门店且门店认证状态为已认证或待优化
                result.addAll(pageQueryResponse.getShopInfos().stream()
                        .filter(info -> "01".equals(info.getShopStatus()))
                        .filter(info -> "01".equals(info.getShopInfoStatus()) || "02".equals(info.getShopInfoStatus()))
                        .collect(Collectors.toList()));
            }
            totalPages = pageQueryResponse.getTotalPages();
            currentPage++;
        } while (currentPage <= totalPages);

        return result;
    }
}
